class Goods {
    constructor() {
        const data = localStorage.getItem("qf-goods-data");
        this.goods = data ? JSON.parse(data) : [];
    }

    time = 500;

    // 获取商品
    getGoods() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(this.goods);
            }, this.time);
        });
    }

    // 创建商品
    createGoods(params) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (!params) {
                    reject("不能不传");
                    return;
                }
                console.log(params, this.goods);
                this.goods = [...this.goods, { ...params }];
                resolve("成功");
                this.keepData();
            }, this.time);
        });
    }

    // 删除商品
    delGoods(index) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (typeof index !== "number") {
                    reject("必须传数值");
                }
                const goods = [...this.goods];
                goods.splice(index, 1);
                this.goods = goods;
                resolve();
                this.keepData();
            }, 2000);
        });
    }

    // 修改商品
    updateGoods(index, data) {
        return new Promise((resolve, reject) => {
            if (typeof index !== "number") {
                reject("必须传数值");
            }

            const goods = [...this.goods];
            goods[index] = data;

            this.goods = [...goods];
            resolve();
            this.keepData();
        });
    }

    // 获取商品详情
    getGoodsDetail(index) {
        return new Promise((resolve, reject) => {
            if (typeof index !== "number") {
                reject("必须传数值");
            }
            resolve(this.goods[index]);
        });
    }

    // 保存商品到本地
    async keepData() {
        const data = await this.getGoods();
        localStorage.setItem("qf-goods-data", JSON.stringify(data));
    }
}

export default new Goods();
